import { Switch } from "react-router-dom"

let initdata = {
   arr:[],
   shoparr:[],// 购物车得数据
   checkAll:false
    
}
let shopReducer = (state=initdata,{type,payload})=>{
    let newarr = JSON.parse(JSON.stringify(state.arr))
    let newShoparr = JSON.parse(JSON.stringify(state.shoparr))
     switch (type) {
        case "getList":
            newarr = payload
            return {
                ...state,
                arr:newarr
            }
        case "addShop":
            // 没有加入过购物车在去加入购物车
            let finnINEDX =state.shoparr.findIndex((item)=>{
               return  item.id == payload.id   
            })
            if (finnINEDX !== -1) {
                alert("您已经加入过购物车了")
            } else {
                newShoparr.push(payload)
            }
            return {
                ...state,
                shoparr:newShoparr
            }
        case "Add":
           let newShoparr1 = state.shoparr.map((item)=>{
               if (item.id == payload) {
                   item.number++
               }
               return item
            })
            return {
                ...state,
                shoparr:newShoparr1
            }
        case "Del":
            let newShoparr2 = state.shoparr.map((item)=>{
                if (item.id == payload) {
                    item.number--
                    if ( item.number == 0) {
                        alert("不能在减l")
                    }
                }
                return item
                })
                return {
                    ...state,
                    shoparr:newShoparr2
                }
        case "checkitem":
            let newShoparr3 =  state.shoparr.map((item)=>{
                if (item.id == payload) {
                    item.flag = !item.flag
                }
                return item
             })
             let flagALL = state.shoparr.every((item)=>{ // 如果每一项得checked属性都为true，则全选按钮亮，有一项为false，全选按钮灭
                    return item.flag
             })
             return {
                 ...state,
                 shoparr:newShoparr3,
                 checkAll:flagALL
             }
        case "checkall":

            state.checkAll = !state.checkAll
            let flag =  state.checkAll
            let newShopArr5 = state.shoparr.map((item,index)=>{
            item.flag = flag
            return item
            })
        return {
            ...state,
            checkAll:flag,
            shoparr:newShopArr5
        }
       
        default:
            return {
                ...state
            }


     }
}
export default shopReducer